<?php
include '../../../wp-blog-header.php';

$Record = new Pod('deal');
$where = "t.camp_end < ".fix_date()."&& brand.id='246'";
$Record->findRecords('t.camp_end DESC', -1,$where);
$dealsFound = $Record->getTotalRows();

function download_page($path){
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_URL,$path);
              curl_setopt($ch, CURLOPT_FAILONERROR,1);
              curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
              curl_setopt($ch, CURLOPT_TIMEOUT, 15);
              $retValue = curl_exec($ch);                      
              curl_close($ch);
              return $retValue;
      }

if($dealsFound > 0)
{
    while($Record->fetchRecord())
    {
      $deal_code = $Record->get_field('short');
      $url = 'http://buzzr:password@api.goibibo.ibibo.com/api/deals/description/code/'.$deal_code.'?format=json';
      $curl_json_output = download_page($url);
      $json_decoded = json_decode($curl_json_output, true);

      if(date('Ymd',strtotime($json_decoded['data']['0']['exp_date'])) > date('Ymd',strtotime($Record->get_field('camp_end'))))
      {
        $deal_id = $Record->get_field('id');
        
        $columns_deal['dealcheck'] = '1';
        $columns_deal['quickcamp'] = '1';
        $columns_deal['daily'] = '0';
        $columns_deal['camp_end'] = $json_decoded['data']['0']['exp_date'];
        
        $ext_image_url = $Record->get_field('ext_image_url');
        if(empty($ext_image_url))
        {
          $columns_deal['ext_image_url'] = $json_decoded['data'][0]['description'][0]['image2'];
        }
        
        $columns_deal['short'] = pods_sanitize(strip_tags($json_decoded['data']['0']['description'][0]['highlights']));
        $columns_deal['terms'] = pods_sanitize(strip_tags($json_decoded['data']['0']['description'][0]['terms']));
        
        $api = new PodAPI();
        
        $params = array('datatype' => 'deal','tbl_row_id' => $deal_id, 'columns' => $columns_deal);
        $api->save_pod_item($params);
      }
    }
}
?>
